package com.guomei.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.guomei.configs.AliyunOssConfig;
import com.guomei.service.AliyunOssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 阿里云OSS服务实现类
 */
@Service
@Slf4j
public class AliyunOssServiceImpl implements AliyunOssService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    /**
     * 日期格式化
     */
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 上传文件
            return uploadFile(inputStream, originalFilename);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败");
        }
    }

    @Override
    public String uploadFile(InputStream inputStream, String fileName) {
        try {
            // 生成文件存储路径
            String filePath = generateFilePath(fileName);

            // 设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
            metadata.setContentDisposition("inline;filename=" + fileName);

            // 上传文件
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePath, inputStream, metadata);

            // 拼接文件访问URL
            return aliyunOssConfig.getDomain() + "/" + filePath;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("输入流关闭失败", e);
            }
        }
    }

    @Override
    public boolean deleteFile(String fileUrl) {
        try {
            // 从URL中获取文件路径
            String filePath = fileUrl.replace(aliyunOssConfig.getDomain() + "/", "");

            // 删除文件
            ossClient.deleteObject(aliyunOssConfig.getBucketName(), filePath);
            return true;
        } catch (Exception e) {
            log.error("文件删除失败", e);
            return false;
        }
    }

    @Override
    public String getTempAccessUrl(String fileUrl, Date expiration) {
        try {
            // 从URL中获取文件路径
            String filePath = fileUrl.replace(aliyunOssConfig.getDomain() + "/", "");

            // 生成带签名的临时访问URL
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
                    aliyunOssConfig.getBucketName(), filePath);
            request.setExpiration(expiration);

            URL url = ossClient.generatePresignedUrl(request);
            return url.toString();
        } catch (Exception e) {
            log.error("生成临时访问URL失败", e);
            throw new RuntimeException("生成临时访问URL失败");
        }
    }

    /**
     * 生成文件存储路径
     */
    private String generateFilePath(String fileName) {
        // 生成日期目录
        String datePath = sdf.format(new Date());
        // 生成随机文件名，避免重复
        String randomStr = generateRandomStr(6);
        // 获取文件扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf("."));

        // 拼接文件路径: 前缀/日期/随机字符串+扩展名
        return aliyunOssConfig.getDir().getPrefix() + datePath + "/" + randomStr + fileExt;
    }

    /**
     * 生成随机字符串
     */
    private String generateRandomStr(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 根据文件后缀获取ContentType
     */
    private String getContentType(String fileExt) {
        if (fileExt.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (fileExt.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (fileExt.equalsIgnoreCase(".jpeg") || fileExt.equalsIgnoreCase(".jpg")) {
            return "image/jpeg";
        }
        if (fileExt.equalsIgnoreCase(".png")) {
            return "image/png";
        }
        if (fileExt.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (fileExt.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (fileExt.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (fileExt.equalsIgnoreCase(".pptx") || fileExt.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (fileExt.equalsIgnoreCase(".docx") || fileExt.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (fileExt.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        // 默认返回二进制流
        return "application/octet-stream";
    }
}
